#!/usr/bin/python
# process_string.py : Sends a sentence to the TRIPS page and gets its semantics analysis and parse.
# using BeautifulSoup HMTL parser.
# Author: Federico Cirett Galan
PGK = "ua_cs665_trips"

from urllib2 import urlopen
#from ClientForm import ParseResponse
from BeautifulSoup import BeautifulSoup
import getopt
import re
import types
import time
import sys
import string
# ROS 
import roslib; roslib.load_manifest('ua_cs665_trips')
import rospy
from std_msgs.msg import String
from ua_cs665_trips.srv import *
#
       
def handle_process_string(req):
    sentence = req.sentence
    query = sentence.replace(' ','+')
    trips_url = "http://www.cs.rochester.edu/research/cisd/projects/trips/parser/cgi/web-parser-xml.cgi?input="
    url = trips_url+query
    print url
    page = urlopen(url)
    soup = BeautifulSoup(page)
    words = soup.findAll('words')
    t_words = words[1].findAll('lisp')
    text_words = t_words[0].text
    print "WORDS"
    print text_words
    tree = soup.findAll('tree')
    t_tree = tree[1].findAll('lisp')
    text_tree = t_tree[0].text
    print "TREE"
    print text_tree
    terms = soup.findAll('terms')
    t_term = terms[1].findAll('lisp')
    text_term= t_term[0].text
    print "RDF"
    print text_term
    return TripsProcessResponse(True)
    
def process_string_server():
    rospy.init_node('process_string_server')
    s = rospy.Service('process_string_server', TripsProcess, handle_process_string)
    print "Ready to process strings."
    rospy.spin()

if __name__ == "__main__":
    process_string_server()
